import pandas as pd
import numpy as np
import differential_behaviour as DFB
import PARISCLASS

'''
This is the main auxiliary function of the main.py file
'''


#===============
RS = DFB.MakeEffectAnalysis()
PC = PARISCLASS.PARIS()
em = 'emissionLongTerm_log'
vars_continous = ['Mills_Ratio', 'Environmental SDGs', 'DirectControl_H', 'firm_size_H', 'investment_log_H', 'Tangibility_H']
vars_named = ['Mills_Ratio', r'\# of initiatives', 'Emission', 'Revenue (log)', 'Investment (log)', 'Tangibility']


class main_results():
    def __init__(self):
        pass
    def table_total(self, ReducedData, size_quartile, target_type, estimation_year, causative_only_actions=False):
        ini_PR, sdgs_PR, DataType, un, algn_population, misl_population = PC.differential_effort(
                                ReducedData, SQ=size_quartile , 
                                target_type = target_type, estimation_year = estimation_year, 
                                show_plots=True,causative_only= causative_only_actions,
                                SAVEPLOT=False, 
                                plot_name='paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))
        paris_FR, _, _, modelALLR, modelBADR, modelGOODR = PC.full_sample_estimation('regression', DataType, un, em, ini_PR, sdgs_PR, target_type,\
                                  vars_continous,vars_named, MakeTable=False,table_name='table_paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))
        paris_FR.columns.name = 'Magnitude of deviation'
        #=====
        paris_FP, _, _, modelALLP, modelBADP, modelGOODP = PC.full_sample_estimation('probit', DataType, un, em, ini_PR, sdgs_PR, target_type,\
                                  vars_continous,vars_named, MakeTable=False,table_name='table_paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))
        paris_FP.columns.name = 'Probability of alignment'

        #===== Print the regression to go in the main text
        print('#======')
        print(paris_FR.to_latex(escape = False).replace('{ll', '{l|a|'))
        print(paris_FP.to_latex(escape = False).replace('{ll', '{l|a|'))
    def table_differential_behaviour(self, ReducedData, size_quartile, target_type, estimation_year, causative_only_actions=False):
        ini_PR, sdgs_PR, DataType, un, algn_population, misl_population = PC.differential_effort(
                                ReducedData, SQ=size_quartile , 
                                target_type = target_type, estimation_year = estimation_year, 
                                show_plots=False,causative_only=causative_only_actions,
                                SAVEPLOT=False, 
                                plot_name='paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))

        _, paris_BR, paris_GR, modelALLR, modelBADR, modelGOODR = PC.full_sample_estimation('regression', DataType, un, em, ini_PR, sdgs_PR, target_type,\
                                  vars_continous,vars_named, MakeTable=False,table_name='table_paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))
        _, paris_BP, paris_GP, modelALLP, modelBADP, modelGOODP = PC.full_sample_estimation('probit', DataType, un, em, ini_PR, sdgs_PR, target_type,\
                                  vars_continous,vars_named, MakeTable=False,table_name='table_paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))


        paris_BR.columns.name = 'Negative excess effort'
        print(paris_BR.to_latex(escape = False).replace('{ll', '{l|a|'))
        paris_GR.columns.name = 'Positive excess effort'
        print(paris_GR.to_latex(escape = False).replace('{ll', '{l|a|'))    

        paris_BP.columns.name = 'Negative excess effort'
        print(paris_BP.to_latex(escape = False).replace('{ll', '{l|a|'))
        paris_GP.columns.name = 'Positive excess effort'
        print(paris_GP.to_latex(escape = False).replace('{ll', '{l|a|'))    

        A = pd.concat((paris_BR['\# of initiatives'], paris_GR['\# of initiatives']), axis = 1)
        A.columns = [r'\textcolor{red}{Negative excess effort}', r'\textcolor{blue}{Positive excess effort}']
        B = pd.concat((paris_BP['\# of initiatives'], paris_GP['\# of initiatives']), axis = 1)
        B.columns = [r'\textcolor{red}{Negative excess effort}', r'\textcolor{blue}{Positive excess effort}']
        dx = pd.concat(dict(Deviation=A, Probability=B), axis = 1)
        print(dx.to_latex(escape = False).replace('{lll', '{lll|').\
              replace('{Deviation}', '{Magnitude of deviation}').\
                  replace('{Probability}', '{Probability of alignment}').\
                      replace('{2}{l}', '{2}{c}'))
            
    def table_by_size(self, ReducedData,  target_type, estimation_year, causative_only_actions=False):
        initiative_sign = pd.DataFrame()
        sdgs_time = pd.DataFrame()
        resR, resP = [], []
        for size_quartile in range(-1,4):
            ini_PR, sdgs_PR, DataType, un, algn_population, misl_population = PC.differential_effort(
                                    ReducedData, SQ=size_quartile , 
                                    target_type = target_type, estimation_year = estimation_year, 
                                    show_plots=False,causative_only=causative_only_actions,
                                    SAVEPLOT=False, plot_name='paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))
            ini_to_save = ini_PR.copy()
            ini_to_save  =  ini_to_save.set_index('SDGs')
            ini_to_save.columns = [r'Q$_'+str(size_quartile+1)+'$']
            initiative_sign = pd.concat((initiative_sign, ini_to_save), axis = 1)
            
            ini_to_save = sdgs_PR.copy()
            ini_to_save  =  ini_to_save.set_index('SDGs')
            ini_to_save.columns = [r'Q$_'+str(size_quartile+1)+'$']
            sdgs_time = pd.concat((sdgs_time, ini_to_save), axis = 1)

            paris_FR, paris_BR, paris_GR, modelALLR, modelBADR, modelGOODR = PC.full_sample_estimation('regression', DataType, un, em, ini_PR, sdgs_PR, target_type,\
                                      vars_continous,vars_named, MakeTable=False,table_name='table_paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))
            resR.append([size_quartile+1, paris_BR.iloc[-1].loc['\# of initiatives'], paris_GR.iloc[-1].loc['\# of initiatives']])

            paris_FP, paris_BP, paris_GP, modelALLP, modelBADP, modelGOODP = PC.full_sample_estimation('probit', DataType, un, em, ini_PR, sdgs_PR, target_type,\
                                      vars_continous,vars_named, MakeTable=False,table_name='table_paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))
            resP.append([size_quartile+1, paris_BP.iloc[-1].loc['\# of initiatives'], paris_GP.iloc[-1].loc['\# of initiatives']])




        resR = pd.DataFrame(resR, columns = ['Size$_q$', '\textcolor{red}{Negative excess effort}', '\textcolor{blue}{Positive excess effort}'])
        resR.columns.name = target_type.replace('_', ' ')
        resR = resR.set_index('Size$_q$')

        resP = pd.DataFrame(resP, columns = ['Size$_q$', '\textcolor{red}{Negative excess effort}', '\textcolor{blue}{Positive excess effort}'])
        resP.columns.name = target_type.replace('_', ' ')
        resP = resP.set_index('Size$_q$')


        dx = pd.concat(dict(Deviation=resR, Probability=resP), axis = 1)
        print(dx.to_latex(escape = False).replace('{lll', '{lll|').\
              replace('{Deviation}', '{Magnitude of deviation}').\
                  replace('{Probability}', '{Probability of alignment}').\
                      replace('{2}{l}', '{2}{c}').\
                          replace('below', 'Below 2$^\circ$C'))


        initiative_sign_ = initiative_sign.apply(np.sign)
        initiative_sign_ = initiative_sign_.mean(axis = 1).sort_values()

        initiative_sign = initiative_sign.rename(columns = {r'Q$_0$': 'Full'})
        init_ = initiative_sign.sort_values(by = 'Q$_3$', ascending = False).round(2)
        means = pd.DataFrame(initiative_sign[initiative_sign.columns[1:]].mean(axis = 1).sort_values())
        means.columns = ['Average']
        init_ = pd.concat((init_, means), axis = 1)
        init_  = init_ .sort_values(by = 'Average', ascending = False)
        init_.index.name = ''
        init_ = init_.round(2)

        c_table_init = RS.excess_effort_table(init_)

        sdgs_time = sdgs_time.rename(columns = {r'Q$_0$': 'Full'})
        sdgs_ = sdgs_time.sort_values(by = 'Q$_3$', ascending = False).round(2)
        means = pd.DataFrame(sdgs_time.mean(axis = 1).sort_values())
        means.columns = ['Average']
        sdgs_ = pd.concat((sdgs_, means), axis = 1)
        sdgs_  = sdgs_ .sort_values(by = 'Average', ascending = False)
        sdgs_.index.name = ''
        sdgs_ = sdgs_.round(2)
        c_table_sdgs = RS.excess_effort_table(sdgs_)
        
        print('#############################################')
        print('########## Differential behaviour ###########')
        print('#############################################')
        print(init_.to_latex(escape=False))
        print(sdgs_.to_latex(escape=False))
        print(c_table_init.to_latex(escape=False))
        print(c_table_sdgs.to_latex(escape=False))
        
    def table_by_time(self, ReducedData,  target_type, estimation_year, causative_only_actions=False):
        initiative_sign = pd.DataFrame()
        sdgs_time = pd.DataFrame()
        resR, resP = [], []
        size_quartile = -1
        for estimation_year in range(2018,2021):
            ini_PR, sdgs_PR, DataType, un, algn_population, misl_population = PC.differential_effort(
                                    ReducedData, SQ=size_quartile , 
                                    target_type = target_type, estimation_year = estimation_year, 
                                    show_plots=False,causative_only=causative_only_actions,
                                    SAVEPLOT=False, plot_name='paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))
            ini_to_save = ini_PR.copy()
            ini_to_save  =  ini_to_save.set_index('SDGs')
            ini_to_save.columns = [estimation_year]
            initiative_sign = pd.concat((initiative_sign, ini_to_save), axis = 1)
            
            ini_to_save = sdgs_PR.copy()
            ini_to_save  =  ini_to_save.set_index('SDGs')
            ini_to_save.columns = [estimation_year]
            sdgs_time = pd.concat((sdgs_time, ini_to_save), axis = 1)


            paris_FR, paris_BR, paris_GR, modelALLR, modelBADR, modelGOODR = PC.full_sample_estimation('regression', DataType, un, em, ini_PR, sdgs_PR, target_type,\
                                      vars_continous,vars_named, MakeTable=False,table_name='table_paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))
            resR.append([estimation_year, paris_BR.iloc[-1].loc['\# of initiatives'], paris_GR.iloc[-1].loc['\# of initiatives']])

            paris_FP, paris_BP, paris_GP, modelALLP, modelBADP, modelGOODP = PC.full_sample_estimation('probit', DataType, un, em, ini_PR, sdgs_PR, target_type,\
                                      vars_continous,vars_named, MakeTable=False,table_name='table_paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))
            resP.append([estimation_year, paris_BP.iloc[-1].loc['\# of initiatives'], paris_GP.iloc[-1].loc['\# of initiatives']])




        resR = pd.DataFrame(resR, columns = ['Year', '\textcolor{red}{Negative excess effort}', '\textcolor{blue}{Positive excess effort}'])
        resR.columns.name = target_type.replace('_', ' ')
        resR = resR.set_index('Year')

        resP = pd.DataFrame(resP, columns = ['Year', '\textcolor{red}{Negative excess effort}', '\textcolor{blue}{Positive excess effort}'])
        resP.columns.name = target_type.replace('_', ' ')
        resP = resP.set_index('Year')


        dx = pd.concat(dict(Deviation=resR, Probability=resP), axis = 1)
        print(dx.to_latex(escape = False).replace('{lll', '{lll|').\
              replace('{Deviation}', '{Magnitude of deviation}').\
                  replace('{Probability}', '{Probability of alignment}').\
                      replace('{2}{l}', '{2}{c}').\
                          replace('below', 'Below 2$^\circ$C'))

        init_ = initiative_sign.sort_values(by = 2020, ascending = False).round(2)
        means = pd.DataFrame(initiative_sign.mean(axis = 1).sort_values())
        means.columns = ['Average']
        init_ = pd.concat((init_, means), axis = 1)
        init_  = init_ .sort_values(by = 'Average', ascending = False)
        init_.index.name = ''
        init_ = init_.round(2)

        c_table_init = RS.excess_effort_table(init_)


        sdgs_ = sdgs_time.sort_values(by = 2020, ascending = False).round(2)
        means = pd.DataFrame(sdgs_time.mean(axis = 1).sort_values())
        means.columns = ['Average']
        sdgs_ = pd.concat((sdgs_, means), axis = 1)
        sdgs_  = sdgs_ .sort_values(by = 'Average', ascending = False)
        sdgs_.index.name = ''
        sdgs_ = sdgs_.round(2)
        c_table_sdgs = RS.excess_effort_table(sdgs_)

        print('#############################################')
        print('########## Differential behaviour ###########')
        print('#############################################')

        print(init_.to_latex(escape=False))
        print(sdgs_.to_latex(escape=False))
        print(c_table_init.to_latex(escape=False))
        print(c_table_sdgs.to_latex(escape=False))
    def table_with_no_SDGs(self, ReducedData, size_quartile, target_type, estimation_year):
        ini_PR, sdgs_PR, DataType, un, algn_population, misl_population = PC.differential_effort(
                                ReducedData, SQ=size_quartile , 
                                target_type = target_type, estimation_year = estimation_year, 
                                show_plots=False,
                                causative_only=False,
                                SAVEPLOT=False, 
                                plot_name='paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))

        _, paris_BR, paris_GR, modelALLR, modelBADR, modelGOODR = PC.full_sample_estimation_withoutSDGs('regression', DataType, un, em, ini_PR, sdgs_PR, target_type,\
                                  vars_continous,vars_named, MakeTable=False,table_name='table_paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))
        _, paris_BP, paris_GP, modelALLP, modelBADP, modelGOODP = PC.full_sample_estimation_withoutSDGs('probit', DataType, un, em, ini_PR, sdgs_PR, target_type,\
                                  vars_continous,vars_named, MakeTable=False,table_name='table_paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))


        paris_BR.columns.name = 'Negative excess effort'
        print(paris_BR.to_latex(escape = False).replace('{ll', '{l|a|'))
        paris_GR.columns.name = 'Positive excess effort'
        print(paris_GR.to_latex(escape = False).replace('{ll', '{l|a|'))    

        paris_BP.columns.name = 'Negative excess effort'
        print(paris_BP.to_latex(escape = False).replace('{ll', '{l|a|'))
        paris_GP.columns.name = 'Positive excess effort'
        print(paris_GP.to_latex(escape = False).replace('{ll', '{l|a|'))    

        A = pd.concat((paris_BR['\# of initiatives'], paris_GR['\# of initiatives']), axis = 1)
        A.columns = [r'\textcolor{red}{Negative excess effort}', r'\textcolor{blue}{Positive excess effort}']
        B = pd.concat((paris_BP['\# of initiatives'], paris_GP['\# of initiatives']), axis = 1)
        B.columns = [r'\textcolor{red}{Negative excess effort}', r'\textcolor{blue}{Positive excess effort}']
        dx = pd.concat(dict(Deviation=A, Probability=B), axis = 1)
        print(dx.to_latex(escape = False).replace('{lll', '{lll|').\
              replace('{Deviation}', '{Magnitude of deviation}').\
                  replace('{Probability}', '{Probability of alignment}').\
                      replace('{2}{l}', '{2}{c}'))
    def table_with_no_actions(self, ReducedData, size_quartile, target_type, estimation_year):
        ini_PR, sdgs_PR, DataType, un, algn_population, misl_population = PC.differential_effort(
                                ReducedData, SQ=size_quartile , 
                                target_type = target_type, estimation_year = estimation_year, 
                                show_plots=False,
                                causative_only=False,
                                SAVEPLOT=False, 
                                plot_name='paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))

        _, paris_BR, paris_GR, modelALLR, modelBADR, modelGOODR = PC.full_sample_estimation_withoutActivity('regression', DataType, un, em, ini_PR, sdgs_PR, target_type,\
                                  vars_continous,vars_named, MakeTable=False,table_name='table_paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))
        _, paris_BP, paris_GP, modelALLP, modelBADP, modelGOODP = PC.full_sample_estimation_withoutActivity('probit', DataType, un, em, ini_PR, sdgs_PR, target_type,\
                                  vars_continous,vars_named, MakeTable=False,table_name='table_paris_'+target_type+'_'+str(size_quartile)+'_'+str(estimation_year))


        paris_BR.columns.name = 'Negative excess effort'
        print(paris_BR.to_latex(escape = False).replace('{ll', '{l|a|'))
        paris_GR.columns.name = 'Positive excess effort'
        print(paris_GR.to_latex(escape = False).replace('{ll', '{l|a|'))    

        paris_BP.columns.name = 'Negative excess effort'
        print(paris_BP.to_latex(escape = False).replace('{ll', '{l|a|'))
        paris_GP.columns.name = 'Positive excess effort'
        print(paris_GP.to_latex(escape = False).replace('{ll', '{l|a|'))    

        A = pd.concat((paris_BR['\# of initiatives'], paris_GR['\# of initiatives']), axis = 1)
        A.columns = [r'\textcolor{red}{Negative excess effort}', r'\textcolor{blue}{Positive excess effort}']
        B = pd.concat((paris_BP['\# of initiatives'], paris_GP['\# of initiatives']), axis = 1)
        B.columns = [r'\textcolor{red}{Negative excess effort}', r'\textcolor{blue}{Positive excess effort}']
        dx = pd.concat(dict(Deviation=A, Probability=B), axis = 1)
        print(dx.to_latex(escape = False).replace('{lll', '{lll|').\
              replace('{Deviation}', '{Magnitude of deviation}').\
                  replace('{Probability}', '{Probability of alignment}').\
                      replace('{2}{l}', '{2}{c}'))